<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'
import type { PlusColumn } from 'plus-pro-components'

import { useAddSupplierCategory, useEditSupplierCategory, useSupplierCategoryInfo } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const treeData = defineModel<boolean>('treeData', { required: true })
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })
const parentId = defineModel<number>('parentId', { required: true })
const type = defineModel<string>('type', { required: true })
const formRef = ref()

type Istate = {
    categoryName: string
    categorySort: number
    isDisable: number
    parentId: number | string
    path: string
}

const initialState = {
    categoryName: '',
    categorySort: 0,
    isDisable: 0,
    parentId: 0,
    path: '',
}

const state = ref<Istate>(cloneDeep(initialState))
const title = computed(() => {
    return type.value === 'edit' ? '编辑供应商类别' : '新增供应商类别'
})

const { isPending: addCategoryPending, mutate } = useAddSupplierCategory()
const { isPending: editCategoryPending, mutate: editCategoryMutate } = useEditSupplierCategory()
const { data: categoryInfo, isLoading: categoryInfoLoading } = useSupplierCategoryInfo(id)
const isPending = computed(() => {
    return addCategoryPending.value || editCategoryPending.value || categoryInfoLoading.value
})
const cascaderProps = { checkStrictly: true, emitPath: false, label: 'categoryName', value: 'id' }
const cascaderOpitons: any = computed(() => {
    return treeData.value ? toRaw(treeData.value) : []
})

watchEffect(() => {
    if (id.value) {
        if (categoryInfo.value) {
            state.value = {
                ...categoryInfo.value,
                parentId: categoryInfo.value.parentId || 0,
            }
        }
    }
    else {
        if (parentId.value) {
            state.value.parentId = parentId.value
            state.value.path = findNodeById(cascaderOpitons.value, parentId.value)?.categoryPath
        }
        else {
            if (!parentId.value) {
                state.value.parentId = 0
                state.value.path = ''
            }
        }
    }
})

const disabledFieldProps = computed(() => {
    return {
        disabled: type.value === 'view',
        maxlength: 20,
    }
})
const disabledNumFieldProps = computed(() => {
    return {
        disabled: type.value === 'view',
        min: 1,
    }
})
const columns: PlusColumn[] = [
    {
        fieldProps: disabledFieldProps.value,
        label: '类别名称',
        prop: 'categoryName',

    },
    {
        label: '上级类别',
        prop: 'parentId',
    },
    {
        fieldProps: disabledNumFieldProps.value,
        label: '排序',
        prop: 'categorySort',
        valueType: 'input-number',
    },
    {
        label: '状态',
        options: [
            {
                label: '启用',
                value: 0,
            },
            {
                label: '禁用',
                value: 1,
            },
        ],
        prop: 'isDisable',
        valueType: 'radio',
    },
]

function validateCategoryName(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入类别名称'))
    }
    if (pattern.test(value))
        callback(new Error('类别名称不允许输入空格'))

    else
        callback()
}

const rules = {
    categoryName: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validateCategoryName,
        },
    ],
}

function findNodeById(nodes, nodeId) {
    for (const node of nodes) {
        if (node.id === nodeId) {
            return node
        }

        if (node.children) {
            const foundNode = findNodeById(node.children, nodeId)
            if (foundNode) {
                return foundNode
            }
        }
    }

    return null
}

function handleChange(e: any) {
    const path = findNodeById(cascaderOpitons.value, e)?.categoryPath
    state.value.path = path
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...state.value,
            parentId: state.value.parentId || 0,
            path: state.value.path || '0',
        }
        console.log(params, 'params')
        const fn = id.value ? editCategoryMutate : mutate

        fn(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    type.value = ''
    id.value = ''
    parentId.value = 0
    formRef.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="600"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <PlusForm ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-parentId>
                <el-cascader v-model="state.parentId"
                             :disabled="!!id || type === 'view'"
                             :options="cascaderOpitons"
                             :props="cascaderProps"
                             clearable
                             filterable
                             :show-all-levels="false"
                             class="w-full"
                             placeholder="请选择上级类别"
                             @change="handleChange($event)"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                    <!-- {{ type === 'view' ? '关闭' : '取消' }} -->
                </el-button>

                <SubmitBtn v-if="type !== 'view'"
                           type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
